package com.szholly.pro.watergas_server.ps.android.service;

import java.util.ArrayList;
import java.util.List;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.ps.android.bean.QcTaskParam;
import com.szholly.pro.watergas_server.ps.android.common.FieldInterceptor;
import com.szholly.pro.watergas_server.ps.android.common.SecurityConfig;
import com.szholly.pro.watergas_server.ps.android.common.SqlUtils;
import com.szholly.pro.watergas_server.ps.android.common.TableRowMap;
import com.szholly.pro.watergas_server.ps.android.common.ValidUtils;
import com.szholly.pro.watergas_server.ps.android.controller.QcControl;
import com.szholly.pro.watergas_server.ps.android.controller.QcDataValid;
import com.szholly.pro.watergas_server.ps.android.controller.QcService;
import com.szholly.pro.watergas_server.ps.data.QcWaterThanRow;
import com.szholly.pro.watergas_server.ps.data.QcWaterThanTable;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONObject;

public class QcTaskBuildBlindSpotStrategy extends QcTaskStrategy {
	public QcTaskBuildBlindSpotStrategy(QcOperationService mOperationService) {
		super(mOperationService);
	}

	@Override
	public List<RowBase> getTaskList(QcTaskParam taskParam) throws Exception {
		return mOperationService.getOperationTaskList(taskParam);
	}

	@Override
	public RowBase addTask(QcTaskParam taskParam) throws Exception {
		return mOperationService.addOperationTask(taskParam);
	}

	@Override
	public void deleteTask(QcTaskParam taskParam) throws Exception {
		mOperationService.deleteOperationTask(taskParam);
	}

	private void executeDeleteTaskContent(String taskCode) {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String sql = "delete from qc_water_than t where t.operation_task_code = @taskCode";
		DataUtil.ExecuteUpdateSql(sql, parms);
	}

	@Override
	public void deleteProcessedTask(QcTaskParam taskParam) throws Exception {
		String userId = taskParam.getUserId();
		String taskCode = taskParam.getTaskCode();

		SecurityConfig config = SecurityConfig.get(userId);
		ValidUtils.isTrue(config.containQcDeleteProcessedTask, "权限不够");
		try {
			DataUtil.beginTransaction();
			executeDeleteTaskContent(taskCode);
			mOperationService.deleteOperationTask(taskParam);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	@Override
	public RowBase getTaskInitData(QcTaskParam taskParam) throws Exception {
		String taskTypeCode = taskParam.getTaskTypeCode();
		String companySql = "select t.companycode \"id\", t.companyname \"name\"\n"
				+ "  from QC_COMPANYINFO t\n"
				+ " where 1 = 1\n";
		if (QcControl.BUILD_SPOT.equals(taskTypeCode)) {
			companySql += " and t.companytype in ('0','1')\n";
		} else {
			companySql += " and t.companytype = '0'\n";
		}
		String monitorSql = "select t.monitoringtypecode \"id\",\n"
				+ "       t1.s_domaincaption   \"name\",\n"
				+ "       t.companycode        \"companyCode\"\n"
				+ "  from qc_companydetailinfo t\n"
				+ "  left join data_defulatdomain t1\n"
				+ "    on t1.s_domaincode = t.monitoringtypecode\n"
				+ " where t1.s_domainname = '质控监测类型'";
		String parameterSql = "select distinct t1.monitorparamcode \"id\",\n"
				+ "       t1.monitorparamname \"name\",\n"
				+ "       t.companycode       \"companyCode\",\n"
				+ "       t1.monitortypecode  \"monitorTypeCode\",\n"
				+ "       t1.monitorparamunit \"unit\"\n"
				+ "  from qc_companyparaminfo t\n"
				+ "  left join qc_monitorparam t1\n"
				+ "    on t1.guid = t.paramguid";

		List<RowBase> companyList = DataUtil.getSelectRows(companySql, null);
		List<RowBase> monitorTypeList = DataUtil.getSelectRows(monitorSql, null);
		List<RowBase> parameterList = DataUtil.getSelectRows(parameterSql, null);
		RowBase resultMap = new RowBase();
		resultMap.put("companyList", companyList);
		resultMap.put("monitorTypeList", monitorTypeList);
		resultMap.put("parameterList", parameterList);		
		return resultMap;
	}

	@Override
	public RowBase getProcessedTaskInitData(QcTaskParam taskParam) throws Exception {
		String taskCode = taskParam.getTaskCode();
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String sql = "select t1.companyname,\n"
				+ "       t2.NAME,\n"
				+ "       t.RTD,\n"
				+ "       to_char(t.datetime, 'yyyy-mm-dd hh24:mi:ss') dateTime,\n"
				+ "       t.sampleid,\n"
				+ "       t3.S_DOMAINCAPTION,\n"
				+ "       t.scope,\n"
				+ "       t.ATTENUATIONWAY,\n"
				+ "       t.SOLVENT,\n"
				+ "       t.UNSURENESSLIMIT,\n"
				+ "       t.unit\n"
				+ "  from QC_WATER_THAN t\n"
				+ "  left join QC_COMPANYINFO t1\n"
				+ "    on t.companyid = t1.companycode\n"
				+ "  left join (select distinct t.monitorparamname NAME, t.monitorparamcode ID\n"
				+ "               from qc_monitorparam t) t2\n"
				+ "    on t2.ID = t.parmname\n"
				+ "  left join (select S_DOMAINCODE, S_DOMAINCAPTION\n"
				+ "               from data_defulatdomain\n"
				+ "              where s_domainname = '质控监测类型') t3\n"
				+ "    on t3.S_DOMAINCODE = t.monitortype\n"
				+ " where 1 = 1\n"
				+ "   and t.operation_task_code = @taskCode";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		ValidUtils.notEmpty(rows, "数据异常，请联系管理员");
		RowBase resultData = new RowBase();
		String multiCompanyName = "";
		for (RowBase rowBase : rows) {
			multiCompanyName += rowBase.getSafeString("companyname") + ",";
		}
		RowBase rowBase = rows.get(0);
		multiCompanyName = multiCompanyName.substring(0, multiCompanyName.length() - 1);
		resultData.put("dateTime", rowBase.getSafeString("dateTime"));
		resultData.put("sampleId", rowBase.getSafeString("sampleId"));
		resultData.put("value", rowBase.getSafeString("RTD"));
		resultData.put("companyName", multiCompanyName);
		resultData.put("monitorTypeName", rowBase.getSafeString("S_DOMAINCAPTION"));
		resultData.put("parameterName", rowBase.getSafeString("NAME"));
		resultData.put("SCOPE", rowBase.getSafeString("SCOPE"));
		resultData.put("ATTENUATIONWAY", rowBase.getSafeString("ATTENUATIONWAY"));
		resultData.put("SOLVENT", rowBase.getSafeString("SOLVENT"));
		resultData.put("UNSURENESSLIMIT", rowBase.getSafeString("UNSURENESSLIMIT"));
		resultData.put("UNIT", rowBase.getSafeString("UNIT"));
		return resultData;
	}

	@Override
	public void saveTask(QcTaskParam taskParam) throws Exception {
		String data = taskParam.getData();
		JSONObject dataObject = JSONObject.fromObject(data);
		JSONObject taskJson = dataObject.getJSONObject("taskBean");
		List<TableRowMap> list = TableRowMap.get(dataObject.getJSONArray("valueList"), "QC_WATER_THAN");
		String taskCode = taskJson.optString("TASK_CODE");
		String taskDes = taskJson.optString("TASK_DESC");
		QcDataValid.monitorStationBlindSpotSaveData(list);
		try {
			DataUtil.beginTransaction();
			preFinishOperationTask(taskCode, taskDes);
			SqlUtils.prepareInsert(list);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	@Override
	public void updateTask(QcTaskParam taskParam) throws Exception {
		String data = taskParam.getData();
		String taskCode = taskParam.getTaskCode();
		JSONObject dataObject = JSONObject.fromObject(data);
		TableRowMap rowMap = TableRowMap.get(dataObject.getJSONObject("value"), QcWaterThanTable.TABLE_NAME);
		RowBase whereMap = new RowBase();
		whereMap.setValue("OPERATION_TASK_CODE", taskCode);
		FieldInterceptor interceptor = FieldInterceptor.createNotNullInterceptor(QcWaterThanRow.FIELD_Rtd);
		SqlUtils.update(rowMap, whereMap, interceptor);
	}

	public static final String QC_WATER_THAN_THANTYPE_BLIND = "1";
	public static final String QC_WATER_THAN_THANTYPE_SPOT = "2";

	QcService mDomainManager = QcService.get();

	// 树状结构
	public class TreeBean {
		private String name;
		private String id;
		private List<TreeBean> list;

		public TreeBean(String id, String name) {
			this.name = name;
			this.id = id;
			list = new ArrayList<>();
		}

		public void addChild(TreeBean child) {
			list.add(child);
		}

		public String getId() {
			return id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public List<TreeBean> getList() {
			return list;
		}

		public void setList(List<TreeBean> list) {
			this.list = list;
		}

		public void setId(String id) {
			this.id = id;
		}

	}

}
